shipment = {}
shipment.orders;
shipment.orderItem;
shipment.seller;
shipment.sellerId;
shipment.orId;
shipment.pmcodes;
shipment.location;
//list all shipment
shipment.list = function () {
    main.init();
    fly.ajax({
        service:'/shipment/list',
        data:null,
        success:function (result) {
            if (result.status) {
                $("#content").html(fly.template('http://naima.vn/shipment/list.html', {
                    data:result.data
                }));
            } else {
                popup.msg(result.message);
            }
        }
    });
}
shipment.getData = function () {
    if (!shipment.orders) {
        fly.ajax({
            service:'/order/getAll',
            async:false,
            success:function (result) {
                if (result.status) {
                    shipment.orders = result.data;
                }
                else
                    popup.msg('Có lỗi trong quá trình truyền dữ liệu, xin thử lại!');
            }
        });
    }
    if (!shipment.location) {
        fly.ajax({
            service:'/shipment/getLocation',
            async:false,
            success:function (result) {
                if (result.status) {
                    shipment.location = result.data;
                }
                else
                    popup.msg('Có lỗi trong quá trình truyền dữ liệu, xin thử lại!');
            }
        });
    }
}
shipment.getSellerInfo = function (sellerId, orderItem) {
    fly.ajax({
        service:'/shipment/calcuLading',
        data:{sellerId:sellerId, orderItem:orderItem},
        loading:false,
        success:function (result) {
            if(result.data.sellerId != null){
                if (result.data.city) {
                    shipment.getCityDetail(result.data.city, 2);
                }
                if (result.data.districts) {
                    shipment.getDistrictDetail(result.data.districts, 2);
                }
                $('.from').val(result.data.address);
                $('.s-name').val(result.data.contact);
            }
            $.each(result.data, function () {

                    $.each(result.data, function () {
                        if (this.from_city_id) {
                            shipment.getCityDetail(this.from_city_id, 2);
                        }
                        if (this.from_district_id) {
                            shipment.getDistrictDetail(this.from_district_id, 2);
                        }
                        $('.from').val(this.address);
                    });
            });
        }
    });
}
shipment.fillSellerCityId = function (id) {
    fly.ajax({
        service:'/shipment/getCityById',
        data:{id:id},
        success:function (result) {
            if (result.status) {
                $('.from').val(result.data.name);
            }
            else
                popup.msg('Có lỗi trong quá trình truyền dữ liệu, xin thử lại!');
        }
    });
}
shipment.checkType = function (orderId) {
    fly.ajax({
        service:'/shipment/GetByOrderId',
        data:{id:orderId},
        success:function (result) {
            if (result.status) {
                if (result.data == null || result.data.shipmentType != 1) {
                    $('.redfont').remove();
                    $('#sl-shipmentType').parent().append('<div style="margin-left:123px;" class="redfont">Bạn chưa tạo vận thu tiền</div>');
                    $('#sl-shipmentType').val(1);
                }
            }
            else
                popup.msg('Có lỗi trong quá trình truyền dữ liệu, xin thử lại!');
        }
    });
}
// check điều kiện cho đơn hàng
shipment.checkSeller = function (data, orderItemId) {

    $('#_orderitems').html('');
	var sellerId;

    if (!orderItemId) {
        $.each(data, function () {
            var tmp = 'Hàng trong nước';
            if (this.sellerId == 1) {
                tmp = 'Hàng nhập khẩu';
            }
            shipment.sellerId = this.sellerId;
            if ($('#sl-shipmentType').val() == 3)
                $('#_orderitems').append('<option selected value="' + this.id + '" sellerId="' + this.sellerId + '">NM' + this.id + ' (' + tmp + ')</option>');
            if ($('#sl-shipmentType').val() == 1)
                if (this.sellerId == 1)
                    $('#_orderitems').append('<option selected value="' + this.id + '" sellerId="' + this.sellerId + '">NM' + this.id + ' (' + tmp + ')</option>');
            if ($('#sl-shipmentType').val() == 2)
                if (this.sellerId != 1)
                    $('#_orderitems').append('<option selected value="' + this.id + '" sellerId="' + this.sellerId + '">NM' + this.id + ' (' + tmp + ')</option>');

        });
    }
    else {
        $.each(data, function () {
            if (orderItemId == this.id) {
                sellerId = this.sellerId;
                return;
            }
        });
        $.each(data, function () {
            $('.price').val(parseFloat(this.price));
            var tmp = 'Hàng trong nước';
            if (this.sellerId == 1)
                tmp = 'Hàng nhập khẩu';
            $('.itemName').val(this.itemName);
            shipment.sellerId = this.sellerId;

            if (orderItemId != this.id) {
                if (this.sellerId == sellerId)
                    $('#_orderitems').append('<option selected value="' + this.id + '" sellerId="' + this.sellerId + '">NM' + this.id + ' (' + tmp + ')</option>');
            }
            else
                $('#_orderitems').append('<option selected value="' + this.id + '" sellerId="' + this.sellerId + '">NM' + this.id + ' (' + tmp + ')</option>');
        });
    }
    if ($('#sl-shipmentType').val() == 1 || $('#sl-shipmentType').val() == 3 && shipment.sellerId == 1) {
        if (document.location.href.split('#')[1].split('/')[0] == "order") {
            shipment.getSellerInfo(1, shipment.orId);
            //  return;
        } else {
            shipment.getSellerInfo(1, shipment.orderItem);
        }
    }
    if ($('#sl-shipmentType').val() == 2) {
        $('.create').html('');
        $('.create').append('Bước 1: Tạo vận đơn COD');
        if (parseInt(shipment.sellerId) > 1) {
            shipment.getSellerInfo(shipment.sellerId, shipment.orderItem);
        }
    }

    if ($('#sl-shipmentType').val() == 1) {
        $('.create').html('');
        $('.s-name').val('Văn phòng naima');
        $('.create').append('Bước 1: Tạo vận đơn THU TIỀN');
    }

    if ($('#sl-shipmentType').val() == 3) {
        $('.create').html('');
        $('.s-name').val('Văn phòng naima');
        $('.create').append('Bước 1: Tạo vận đơn GIAO HÀNG');
    }

    if ($('#sl-shipmentType').val() == 3 && shipment.sellerId != 1) {
        if (parseInt(shipment.sellerId) > 1) {
            shipment.getSellerInfo(shipment.sellerId, shipment.orderItem);
        }
    }
}
shipment.appendOrderItem = function (orderId, orderItemId) {
    fly.ajax({
        service:'/order/getOrderItem',
        data:{id:orderId},
        success:function (rs) {
            if (rs.status) {
                shipment.getOrderDetail(orderId);
                $('#_orderitems').html('');
                shipment.checkSeller(rs.data, orderItemId);
                $('#sl-shipmentType').change(function () {
                    shipment.checkSeller(rs.data, orderItemId);
                });
            }
            else
                popup.msg('Có lỗi xảy ra trong quá trình truyền dữ liệu, xin thử lại!');
        }
    });
}
shipment.viewShipment = function (id) {
    fly.ajax({
        service:'/shipment/get',
        data:{id:id},
        success:function (rs) {
            if (rs.status) {
                popup.open('popup-shipment-form', 'Thông tin vận đơn', fly.template('http://naima.vn/shipment/formorder.html', {
                    data:rs.data
                }), [
                    {
                        title:'Cập nhật',
                        fn:function () {
                            fly.ajax({
                                service:'/shipment/update',
								data: {id: id},
                                success:function (result) {
									if(!result)
										popup.msg(result.message);
									else{
										popup.msg('Cập nhật thành công.');
										popup.close('popup-shipment-form');
										if (document.location.href.split('#')[1].split('/')[0] == "order") {
											order.shipments = null;
											order.list();
											return;
										}
										shipment.list();
									}
                                }
                            });
                        }
                    },
                    {
                        title:'Hủy bỏ',
                        fn:function () {
                            popup.close('popup-shipment-form');
                        }
                    },
                ]);
                $('#sl-shipmentStatus').val(rs.data.shipmentStatus);
                shipment.getCityDetail(rs.data.city_from_id, 0);
                shipment.getDistrictDetail(rs.data.district_from_id, 0);
                shipment.getCityDetail(rs.data.city_to_id);
                shipment.getDistrictDetail(rs.data.district_to_id);
                if (rs.data.status == -1) {
                    $('#sl-shipmentStatus').prop("disabled", true);
                }
                fly.ajax({
                    service:'/order/get',
                    data:{id:rs.data.orderId},
                    success:function (result) {
                        $('.r-name').append(result.data.receiverName);
                        $('.r-phone').append(result.data.receiverPhone);
                    }
                });
                fly.ajax({
                    service:'/PaymentCode/list',
                    async:false,
                    success:function (rsdata) {
                        if (rsdata.status)
                            shipment.pmcodes = rsdata.data;
                        else {
                            popup.msg('Có lỗi xảy ra trong quá trình truyền dữ liệu, xin thử lại!');
                        }
                    },
                });
                if (rs.data.shipmentType == 1) {
                    order.oid = rs.data.orderId;
                    $('.pm').html('');
                    $('.pm').append('<label style="width:118px;">Trạng thái thu tiền:</label><span>Chưa tạo hóa đơn thu tiền. <a onclick="shipment.createPmCode(order.oid)">Click vào đây</a> để tạo mã thu tiền</span></span>');
                    ;
                    if (shipment.pmcodes) {
                        $.each(shipment.pmcodes, function () {
                            if (this.orderId == rs.data.orderId) {
                                $('.pm').html('');
                                $('.print').show();
                                $('.pm').append('<label style="width:118px;">Trạng thái thu tiền:</label><span>Đã tạo hóa đơn phiếu thu, mã phiếu thu: ' + this.code + '</span>');
                            } else {
                                $('.pm').html('');
                                $('.pm').append('<label style="width:118px;">Trạng thái thu tiền:</label><span>Chưa tạo phiếu thu. <a onclick="shipment.createPmCode(order.oid)">Click vào đây</a> để tạo phiếu thu</span>');
                                ;
                            }
                        });
                    }
                }
            }
            else
                popup.msg(rs.message);
        }
    });
}
//tạo phiếu thu
shipment.createPmCode = function (orderId) {
    fly.ajax({
        service:'/PaymentCode/create',
        data:{
            orderId:orderId
        },
        success:function (result) {
            popup.msg(result.message);
            $('.pm').html('');
            $('.print').show();
            $('.pm').append('<label style="width:118px;">Trạng thái thu tiền:</label><span>Đã tạo hóa đơn thu tiền, mã thu tiền: ' + result.data + '</span>');
        }
    });
}
shipment.createNew = function (orderId, shipmentType, orderItemId) {
    shipment.getData();
	fly.ajax({
		service: '/order/getById',
		data: {id: orderId},
		success: function(data){			
			popup.open('popup-shipment-form', 'Tạo vận đơn mới', fly.template('http://naima.vn/shipment/form.html', {
				data:data.data
			}), [
				{
					title:'Tiếp tục',
					fn:function () {
						if (!$('#_orderitems').val()) {
							$('#_orderitems').parent().append('<div class="redfont">Vui lòng chọn sản phẩm</div>');
							return;
						}
						$('._orderItemId').val($('#_orderitems').val().join(','));
						if (document.location.href.split('#')[1].split('/')[0] == "order") {
							$('#_orders').removeAttr('disabled');
							$('#sl-shipmentType').removeAttr('disabled');
						}
						fly.submit({
							id:'shipment-form',
							service:'/shipment/form',
							success:function (result) {
								popup.msg(result.message);

								popup.close('popup-shipment-form');
								if (document.location.href.split('#')[1].split('/')[0] == "order") {
									order.shipments = null;
									order.list();
									popup.msg('Thêm thành công!');
									return;
								}
								popup.msg('Thêm thành công!');
								shipment.list();
								shipment.viewShipment(result.data.id);
							}
						});
					}
				},
				{
					title:'Hủy bỏ',
					fn:function () {
						popup.close('popup-shipment-form');
					}
				},
			]);
			shipment.orId = orderId;
			if(orderId){
				shipment.orderItem = orderId;
			}
			$('#_orders').html('<option value="0">Chọn hóa đơn</option>');
			$.each(shipment.orders, function () {
				$('#_orders').append('<option onclick="shipment.appendOrderItem(' + this.id + ')" value="' + this.id + '">NMBIN' + this.id + '</option>');
				if (this.id == orderId) {
					$('#receiverAddress').val(this.receiverAddress);
				}
			});
			$.each(shipment.location, function () {
				$('#_location').append('<option value=' + this.id + '>' + this.name + '</option>');
				$('#_from_location').append('<option value=' + this.id + '>' + this.name + '</option>');
			});
			shipment.getDistricts(1);
			$('#_location').change(function () {
				shipment.getDistricts($(this).val());
			});
			$('#_from_location').change(function () {
				shipment.getDistricts($(this).val(), 2);
			});
			if (orderId != 0)
				shipment.appendOrderItem(orderId, orderItemId);

			$('#_orders').change(function () {
				shipment.orderItem = $(this).val();
				shipment.appendOrderItem($(this).val(), orderItemId);
				shipment.getOrderDetail($(this).val());

			});

			$('#sl-shipmentType').val(shipmentType);
			if (document.location.href.split('#')[1].split('/')[0] == "order") {
				$('#_orders').attr('disabled', 'disabled').val(orderId);
				//$('#sl-shipmentType').attr('disabled', 'disabled');
			}
			$('#_location').val(data.data.receiverLocationId);
		}
	});
}
shipment.getDistricts = function (locationid, type) {
    fly.ajax({
        service:'/shipment/getDistricts',
        data:{locationId:locationid},
        success:function (result) {
            if (result.status) {
                if (type == 2) {
                    $('#_from_district').html('');
                    $.each(result.data, function () {
                        $('#_from_district').append('<option value=' + this.id + '>' + this.name + '</option>');
                    });
                } else {
                    $('#_district').html('');
                    $.each(result.data, function () {
                        $('#_district').append('<option value=' + this.id + '>' + this.name + '</option>');
                    });
                }

            }
            else
                popup.msg('Có lỗi trong quá trình truyền dữ liệu, xin thử lại!');
        }
    });
}
//get city detail
shipment.getCityDetail = function (id, type) {
    fly.ajax({
        service:'/shipment/getCityById',
        data:{id:id},
        success:function (result) {
            if (result.status) {
                if (type == 0) {
                    $('.city_from_').append(result.data.name);
                } else if (type == 2) {
                    $('#_from_location').val(result.data.id);
                } else if (type == 3) {
                    $('#_location').val(result.data.id);
                }
                else {
                    $('.city_to_').append(result.data.name);
                }
            }
            else
                popup.msg('Có lỗi trong quá trình truyền dữ liệu, xin thử lại!');
        }
    });
}
shipment.getDistrictDetail = function (id, type) {
    fly.ajax({
        service:'/shipment/getDistrictsById',
        data:{id:id},
        success:function (result) {
                if (result.data != null) {
                    if (type == 0) {
                        $('.district_from_').append(result.data.name);
                    } else if (type == 2) {
                        $('.fr_dis').remove();
                        $('#_from_district').append('<option class="fr_dis" value=' + result.data.id + '>' + result.data.name + '</option>');
                    } else if (type == 3) {
                        $('#_district').html('');
                        $('#_district').append('<option value=' + result.data.id + '>' + result.data.name + '</option>');
                    } else {
                        $('.district_to_').append(result.data.name);
                    }
                }
        }
    });
}
shipment.getOrderDetail = function (id) {
    fly.ajax({
        service:'/order/get',
        data:{id:id},
        loading:false,
        success:function (result) {
            $('.r-email').val(result.data.receiverEmail);
            $('.r-phone').val(result.data.receiverPhone);
            $('.r-name').val(result.data.receiverName);
            $('#receiverAddress').val(result.data.receiverAddress);
            shipment.getCityDetail(result.data.receiverLocationId, 3);
            if(result.data.receiverDistrictId > 0){
                shipment.getDistrictDetail(result.data.receiverDistrictId, 3);
            }
        }
    });
}

